# Values set at CMake configure time
set(CBDIR "@CMAKE_CURRENT_BINARY_DIR@")
set(CSDIR "@CMAKE_CURRENT_SOURCE_DIR@")
set(GCHECKER_CF "@GCHECKER_CLEAN_FILE@")
set(LOGFILE "@LOG_FILE@")

set(BU_DIR_CACHE ${CBDIR}/cache)
set(LIBRT_CACHE ${CBDIR}/rtcache)
set(ENV{BU_DIR_CACHE} ${BU_DIR_CACHE})
set(ENV{LIBRT_CACHE} ${LIBRT_CACHE})
file(REMOVE_RECURSE "${BU_DIR_CACHE}")
file(REMOVE_RECURSE "${LIBRT_CACHE}")
file(MAKE_DIRECTORY "${BU_DIR_CACHE}")
file(MAKE_DIRECTORY "${LIBRT_CACHE}")

file(WRITE "${LOGFILE}" "Starting gchecker test run\n")

# The executable locations aren't know at CMake configure time, so one of them
# is passed in via the EXEC variable at runtime.  De-quote it and assign it to
# the appropriate variable.
string(REPLACE "\\" "" GCHECKER "${EXEC}")
if(NOT EXISTS "${GCHECKER}")
  file(WRITE "${LOGFILE}" "regress_gchecker not found at location \"${GCHECKER}\" - aborting\n")
  message(FATAL_ERROR "Unable to find regress_gchecker, aborting.\nSee ${LOGFILE} for more details.")
endif(NOT EXISTS "${GCHECKER}")

# Clean up in case we've run before
execute_process(
  COMMAND "@CMAKE_COMMAND@" -E remove -f "${GCHECKER_CF}"
)
execute_process(COMMAND "@CMAKE_COMMAND@" -E remove_directory "${CBDIR}/gchecker_test.g.ck")

file(APPEND "${LOGFILE}" "Running gchecker:\n${GCHECKER} ${CSDIR}/gchecker_test.g\n")

execute_process(
  COMMAND "${GCHECKER}" "${CSDIR}/gchecker_test.g"
  RESULT_VARIABLE gchecker_result
  OUTPUT_VARIABLE gchecker_log
  ERROR_VARIABLE gchecker_log
  WORKING_DIRECTORY ${CBDIR}
)
file(APPEND "${LOGFILE}" "${gchecker_log}")
set(gchecker_log)
if(NOT EXISTS "${CBDIR}/gchecker_test.g.ck/ck.gchecker_test.g.overlaps")
  file(APPEND "${LOGFILE}" "\n\nError: return code ${gchecker_result}")
  file(READ "${LOGFILE}" LOG)
  message(
    FATAL_ERROR
    "${GCHECKER} failed to process gchecker_test.g, aborting.\nSee ${CBDIR}/gchecker.log for more details.\n${LOG}"
  )
endif(NOT EXISTS "${CBDIR}/gchecker_test.g.ck/ck.gchecker_test.g.overlaps")

if(gchecker_result)
  file(APPEND "${LOGFILE}" "\n\nError: return code ${gchecker_result}")
  file(READ "${LOGFILE}" LOG)
  message(FATAL_ERROR "[gchecker] Failure, see ${LOGFILE} for more info.\n${LOG}")
endif(gchecker_result)

# Cleanup
execute_process(
  COMMAND "@CMAKE_COMMAND@" -E rm -rf ${BU_DIR_CACHE}
)
execute_process(
  COMMAND "@CMAKE_COMMAND@" -E rm -rf ${LIBRT_CACHE}
)

# Local Variables:
# tab-width: 8
# mode: cmake
# indent-tabs-mode: t
# End:
# ex: shiftwidth=2 tabstop=8
